<template>
	<view class="identification">
		<!--
		<u-navbar title="认证信息" @rightClick="rightClick" :background="{backgroundColor:'#d3f4fe'}" :is-back="!serialno"
			titleBold>
		</u-navbar>
		-->
		<u-navbar title="认证信息" @rightClick="rightClick" :background="{backgroundColor:'#d3f4fe'}" titleBold>
		</u-navbar>
		<view class="identification-step">
			<uv-steps :current="stepCurrent" activeColor="#00C7FB">
				<uv-steps-item title="身份验证">
				</uv-steps-item>
				<uv-steps-item title="商家认证"></uv-steps-item>
				<uv-steps-item title="收款卡认证"></uv-steps-item>
			</uv-steps>
		</view>
		<view class="identification-content">
			<identity v-show="stepCurrent==0" :terminalInto="terminalInto" @idCardSubmit="idCardSubmit" :type="4"
				:sanSerialno="serialno" :res="res" :formData="identityData" ref="identity"></identity>
			<Merchant v-show="stepCurrent==1" :res="res" :terminalInto="terminalInto" @backSubmit="backSubmit"
				@merchantSubmit="merchantSubmit" :type="1" :formData="merchantData" ref="Merchant">
			</Merchant>
			<bindCard v-show="stepCurrent==2" :res="res" :terminalInto="terminalInto" @backSubmit="backSubmit"
				ref="bindCard" @cardSubmit="cardSubmit" :type="4" :formData="cardData">
			</bindCard>
			<authResult v-show="stepCurrent==3" :res="res" :terminalInto="terminalInto" @backSubmit="backSubmit"
				ref="authResult" @cardSubmit="cardSubmit" :type="4" :formData="cardData">
			</authResult>
		</view>
	</view>
</template>

<script>
	import bindCard from "./card"
	import authResult from "./authResult"
	import identity from "./identity"
	import Merchant from "./merchant"
	import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
	import {
		nameAuth,
		authInfoSave,
		//informationQuery,
		queryCustomer,
		checkUser,
		scanLogin,
		scanCreateUser,
		scanIncome,
		scanGetS,
		jumpToUrl
	} from '_a/user';

	export default {
		components: {
			bindCard,
			identity,
			Merchant,
			authResult
		},
		data() {
			return {
				stepCurrent: 0,
				formData: {},
				// addressInfo: {},
				cardData: "",
				identityData: "",
				merchantData: "",
				serialno: '',
				res: null
			}
		},
		computed: {
			// 是否机具扫码进入
			terminalInto() {
				return this.$store.getters.terminalInto || false
			}
		},
		created() {

		},
		onBackPress(o) {

			if (o.from == 'backbutton') {
				console.log(this.serialno, o);
				if (this.serialno) {
					return true
				} else {
					return false
				}
			}
		},
		async onLoad(o) {
			if (o.sn) {
				this.$store.commit('SET_TOKEN_MERCH', '')
				let pass = true // 是否通过校验,没通过,清空token
				this.$store.commit('SETTerminalInto', true)
				//alert(this.$store.getters.terminalInto);

				this.$tip.loading('机具校验中..')
				let scanSData = await scanGetS(o.sn)
				this.$tip.loaded()
				if (scanSData.code != 200) {
					pass = false
					return this.$tip.modal({
						title: '提示',
						content: '机具校验未通过',
						showCancel: false
					})
				}
				
				this.serialno = scanSData.data.sn
				
				let urlData = await jumpToUrl(this.serialno)//获取代理商配置的跳转地址
				if(urlData.code == 200 && urlData.data.url != null){
					window.location.href = urlData.data.url+"pages/home/identification/index?sn="+o.sn;
					return;
				}
				
				this.$storage.setStore('serialno', this.serialno)

				// 签名获取params 
				let params = await this.signParams(this.serialno)
				console.log("params:"+JSON.stringify(data));
				let data = await checkUser(params)
				// 已经绑定的机子认为是已经注册成功
				if(data.msg == '该终端已绑定'){
					this.$storage.setStore('auth_bind_status', 1);
					this.$refs.authResult.getData();
					this.stepCurrent=3;
					return;
				}
				if (data.code != 200) {
					pass = false
					this.$tip.modal({
						title: '提示',
						content: data.msg,
						showCancel: false
					})
				} else {
					console.log("---------------data.data.isRegister:"+JSON.stringify(data));
					if (data.data.isRegister && data.data.hasBasicInfo) {
						// 注册过,获取token
						let loginData = await scanLogin(params)
						console.log("---------------loginData:"+JSON.stringify(loginData));
						if (loginData.code == 200) {
							this.$store.commit('SET_TOKEN_MERCH', loginData.data.token)
							const scanSerialno = this.serialno
							let auth_result = await queryCustomer({scanSerialno});
							
							if(auth_result.data && auth_result.data.auditStatus && auth_result.data.auditStatus!=0){
								this.$storage.setStore('auth_bind_status', 0);
								this.$storage.setStore('auth_result', auth_result);
								this.stepCurrent = 3;
								this.$refs.authResult.getData();
							}
						}
					} else {
						let data2
						if (data.data.isRegister && !data.data.hasBasicInfo) {
							// 没有注册过,创建
							data2 = await scanLogin(params)
						} else {
							data2 = await scanCreateUser(params)
						}

						if (data2.code == 200) {
							this.$store.commit('SET_TOKEN_MERCH', data2.data.token)
							await this.$store.dispatch('getUserDetail').then(res => {
								this.res = res
								console.log(res);
							})
						}
					}
					// 加载组件数据
					this.loadingData()
				}
				if (!pass) {
					// 上面校验没通过,清空token,预防保留上一个的扫码token 
					this.$store.commit('SET_TOKEN_MERCH', '')
				}


			} else {
				await this.$store.dispatch('getUserDetail').then(res => {
					this.res = res
					console.log(res);
				})
				this.loadingData();
			}
		},
		onShow() {},
		methods: {
			loadingData() {
				if (this.$refs.identity) {
					this.$refs.identity.loadingInfo()
				}
				if (this.$refs.Merchant) {
					this.$refs.Merchant.loadingInfo()
				}
				if (this.$refs.bindCard) {
					this.$refs.bindCard.loadingInfo()
				}
			},
			// RAS 签名
			async signParams(serialno, phone, code) {
				let params = {
					scanSerialno: serialno,
					scanDate: this.$u.timeFormat(new Date(), 'yyyymmddhhMMss'),
				}
				if (phone) {
					params.scanMobile = phone
				}
				if (code) {
					params.scanSmsCode = code
				}
				let keyList = Object.keys(params).sort().map(item => {
					return params[item]
				})
				let canSignData = keyList.join('')
				console.log(canSignData);
				// 签名
				params.scanSign = await this.getRSAencry(canSignData)
				params.scanAppid = 'abc123456'
				return params
			},
			getRSAencry(str_value) {
				if (typeof a != 'string') {
					str_value = str_value
				}

				let publicKey = this.$config.pubKey

				let jse = new JSEncrypt();

				jse.setPublicKey(publicKey);
				return jse.encrypt(str_value)

			},
			// 获取定位
			getLocal() {
				uni.getLocation({
					type: 'gcj02',
					geocode: "true",
					success: (res) => {
						// let addressInfo = {}
						// addressInfo.registerAddress = res.address.street + res.address.streetNum + res
						// 	.address.poiName;
						// addressInfo.registerProvinceName = res.address.province
						// addressInfo.registerCityName = res.address.city
						// addressInfo.registerAreaName = res.address.district
						// addressInfo.registerLongitude = res.longitude
						// addressInfo.registerLatitude = res.latitude
						// console.log("this.addressInfo",addressInfo)
						// this.addressInfo = addressInfo
						// this.$storage.setStore('addressInfo', addressInfo);
						// if(!addressInfo){
						// 	this.turnAdrr(res.longitude, res.latitude);
						// }
						this.turnAdrr(res.longitude, res.latitude);
					},
					fail: (error) => {
						console.log({
							error
						});
						// this.getSettingInfo();
					}
				});
			},
			turnAdrr(longitude, latitude) {
				let that = this
				let _key = '809698c504a79be7231bd6f448b3bbae'; //高德API key类型：web服务
				uni.request({
					method: 'GET',
					url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
					data: {
						key: _key,
						location: `${longitude},${latitude}`,
						output: 'JSON',
					},
					success: (result) => {
						let res = result.data.regeocode;
						console.log({
							res
						});
						console.log({
							result
						});
						// console.log(res.data.regeocode.formatted_address);
						//用户所在的地理位置信息
						let addressInfo = {}
						addressInfo.registerAddress = res.formatted_address;
						addressInfo.registerProvinceName = res.addressComponent.province
						addressInfo.registerCityName = res.addressComponent.city
						addressInfo.registerAreaName = res.addressComponent.district
						addressInfo.registerLongitude = longitude
						addressInfo.registerLatitude = latitude
						addressInfo.registerAreaCode = res.addressComponent.adcode
						// alert(addressInfo.registerLongitude)
						// uni.showModal({
						// 	title: '地址信息',
						// 	content: addressInfo.registerLongitude,
						// 	success: (res) => {}
						// })
						console.log("that.addressInfo", addressInfo);
						that.addressInfo = addressInfo
						that.$storage.setStore('addressInfo', addressInfo);

					},
					fail: r => {
						console.log({
							r
						});
					}
				});
			},
			// 身份实名
			idCardSubmit(form, stepCurrent) {
				// 未获取定位信息
				// if (!this.addressInfo) {
				// 	//#ifdef APP
				// 	this.getSettingInfo();
				// 	//#endif
				// }
				this.formData = {
					...this.formData,
					...form
				};
				//保存商户进件信息
				let params = {
					...form,
					...this.formData,
				}
				console.log("---------------------------------------");
				console.log(JSON.stringify(params))
				console.log("---------------------------------------");
				
				authInfoSave(params);
				this.stepCurrent = stepCurrent;
			},
			// 上一步
			backSubmit(stepCurrent) {
				this.stepCurrent = stepCurrent;
			},
			async cardSubmit(form, stepCurrent) {
				this.$tip.loading('提交中....');
				let params = {
					...form,
					...this.formData,
					// ...this.addressInfo
				}
				console.log({
					params
				})
				let result
				// 签名获取params
				//if(!params.serialno){
				//	params.serialno = this.$storage.getStore('serialno');
				//}
				let signParams = await this.signParams(params.serialno, params.phone, params.scanSmsCode)
				let scanData = await scanIncome(signParams);
				if (scanData.code == 200) {
					params.serialno = this.$storage.getStore('serialno');
					result = await nameAuth(params);
				}
				// return
				// 加载结束
				this.$tip.loaded();
				// 认证成功!
				let resultType;
				this.$store.dispatch('updateUserInfo');
				if (result.code == 200) {
					this.$storage.removeStore('idCardFormData');
					resultType = 'success';
					let url = encodeURIComponent(result.data);
					
					this.$storage.setStore('registerMerchSuccess', true);
					let nav = this.$nav;
					
					uni.showModal({
						title: '提示',
						content: '提交成功!',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								
							}
						}
					});
					
					
					const scanSerialno = this.serialno
					let auth_result = await queryCustomer({scanSerialno});
					
					this.$storage.setStore('auth_bind_status', 0);
					this.$storage.setStore('auth_result', auth_result);
					this.stepCurrent = 3;
					this.$refs.authResult.getData();
					
				} else {
					resultType = 'fail'
				}
			},
			merchantSubmit(form, stepCurrent) {
				this.formData = {
					...this.formData,
					...form
				};
				//保存商户进件信息
				let params = {
					...form,
					...this.formData,
				}
				authInfoSave(params);
				this.stepCurrent = stepCurrent;
			},
			getSettingInfo() {
				let _this = this
				// 获取定位是否开启
				const appAuthorizeSetting = uni.getAppAuthorizeSetting();
				if (appAuthorizeSetting.locationAuthorized == 'denied') { //定位拒绝
					uni.showModal({
						title: "提示",
						content: "请开启定位权限才能进件成功!",
						success: (res) => {
							uni.openAppAuthorizeSetting({
								success(res) {
									console.log(res)
									_this.getLocal();
								}
							})
						},
					})
				}
			},
			//重新发起获取当前位置授权
			rGetLocation() {
				let _this = this
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							_this.getLocal();
						} else {
							uni.showModal({
								content: '检测到您没打开获取信息功能权限，是否去设置打开？',
								confirmText: "确认",
								cancelText: '取消',
								success: (res) => {
									if (res.confirm) {
										uni.openSetting({
											success: (res) => {
												console.log(res);
												_this.getLocal()
											}
										})
									} else {
										console.log('取消');
										return false;
									}
								}
							})
						}
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.identification {}

	.identification-step {
		background-color: #ffffff;
		padding: 20upx 0 0;

	}

	.identification-content {
		padding: 0upx 0 20upx;
	}

	/deep/.uv-steps-item__wrapper__circle {
		// background-color: #00C7FB !important;
		// color: #ffffff;
		// border: none;
	}
</style>